<!--
  * 公司列表
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-08-15 20:15:49
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="学校编号" class="smart-query-form-item" v-privilege="'system:sign:queryPage'">
        <!-- <a-input style="width: 300px" v-model:value="queryForm.registerschool" placeholder="请输入编号" />F -->
        <a-select v-model:value="queryForm.registerSchool" show-search style="width: 300px" placeholder="请输入编号"
          :options="schooleOptions" :filterOption="filterOption" />
      </a-form-item>
      <a-form-item label="日期" class="smart-query-form-item">
        <a-range-picker v-model:value="queryForm.formState" value-format="YYYY-MM-DD" />
      </a-form-item>
      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" v-privilege="'system:sign:queryPage'">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
          <a-button type="primary" @click="downloadFile"> 下载 </a-button>
          <a-button type="primary" @click="downloadFile2"> 下载附件 </a-button>
          <a-button type="primary" @click="exportToExcel"> 导出表格 </a-button>
        </a-button-group>
      </a-form-item>
      <a-button type="primary" @click="showModal" style="margin-top: 5px;"> 上传附件 </a-button>
      <a-modal v-model:open="open" @ok="handleOk" @cancel="handleCancel" style="max-width: 550px">
        <!-- 上传文件组件 -->
        <a-upload v-model:file-list="fileList" name="file" :multiple="true" :max-count="1"
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76" :customRequest="customRequestFile"
          :showUploadList="false">
          <a-button type="primary">
            <upload-outlined />
            上传文件
          </a-button>
        </a-upload>
        <a-button type="link" v-if="fileName" @click="downloadFiles">报名附件.zip</a-button>
        <h4 style="color: red;margin-top: 5px;">该附件用于教师招聘通过审核后操作手册，请将所有材料打包成zip格式上传</h4>
        <div v-if="percent > 0" style="width: 85%;">
          <a-progress :percent="percent">
            <template #format="percent">
              <span>{{ percent }}%({{ percent == 100 ? '上传成功' : '上传中...' }})</span>
            </template>
          </a-progress>
        </div>
      </a-modal>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false" :hoverable="true">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block"></div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.TEACHERTION.REGISTRATIONrEVIEW"
          :refresh="ajaxQuery" />
      </div>
    </a-row>
    <div>
      <a-tabs v-model:activeKey="activeKey" @tabClick="tabClick">
        <a-tab-pane key="0" tab="未审核" />
        <a-tab-pane key="1" tab="审核通过" force-render />
        <a-tab-pane key="2" tab="审核未通过" />
      </a-tabs>
      <a-table  :scroll="{ x: 1600 }" ref="tableDataref" size="small" :dataSource="tableData" :columns="columns"
        rowKey="employeeId" :pagination="false" :loading="tableLoading" bordered
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ column, record }">
      

          <template v-if="column.dataIndex === 'gender'">
            {{ record.gender == 1 ? '男' : '女' }}
          </template>
          <template v-if="column.dataIndex === 'ethnicGroupId'">
            {{ ethnicGroupList[record.ethnicGroupId - 1] }}
          </template>
     

          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="examine(record.employeeId)" size="small" type="link">审核</a-button>
              <a-button @click="detail(record.employeeId)" size="small" type="link">详情</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize" v-model:current="queryForm.pageNum" v-model:pageSize="queryForm.pageSize"
        :total="total" @change="ajaxQuery" @showSizeChange="ajaxQuery" :show-total="(total) => `共${total}条`" />
    </div>
    <!-- <EnterpriseOperate ref="operateRef" @refresh="ajaxQuery"/> -->
  </a-card>
  <DetailForm ref="detailFormRef" @emitfresh="ajaxQuery"/>
</template>
<script setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { registrationReviewApi } from '/@/api/registrationReview/index';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
import DetailForm from './components/index.vue';
import { loginApi } from '/@/api/system/login-api';
import { useUserStore } from '/@/store/modules/system/user';
import XLSX from 'xlsx';
import { fileApi } from '/@/api/support/file-api';
// import dayjs from 'dayjs'; // 引入 dayjs 来方便处理日期

const baseUrl = import.meta.env.VITE_APP_API_URL;
// 选择表格行
const selectedRowKeyList = ref([]);
//岗位代码
const jobCodeList = ['教师岗位', '其他专业技术岗位', '管理岗位', '工勤技能岗位', '特设岗位', '无其他岗位'];
// 政治面貌
const politicalList = ['中共党员', '中共预备党员', '共青团员', '群众', '其他政治面貌'];
// 婚姻状况
const maritalList = ['未婚', '已婚', '离异', '丧偶'];
// 英语等级
const englishList = ['一级', '二级', '三级', '四级', '五级', '六级', '七级', '八级', '九级'];
// 普通话等级
const mandarinList = ['一级甲等', '一级乙等', '二级甲等', '二级乙等', '三级甲等', '三级乙等'];
// 教师资格证类别
const teacherCardTypeList = [
  '幼儿园教师资格',
  '小学教师资格',
  '初级中学教师资格 ',
  '高级中学教师资格',
  '中等职业学校教师资格',
  '中等职业学校实习指导教师资格',
  '高等学校教师资格',
];
// 教师资格证学科
const SubjectList = ['幼儿园', '小学', '初中', '高中'];
//学位
const academicDegreeList = ['学士', '硕士', '博士'];
// 学历
const educationList = ['本科', '硕士研究生', '博士研究生'];
const ethnicGroupList = ref([]);
const registerTypeList = ref([]);
// 审核状态
const activeKey = ref('0'); // 默认显示 "未审核" 标签页
// --------------------------- 企业表格 列 ---------------------------
//表格列表配置
const columns = ref([
  {
    title: '报名序号',
    dataIndex: 'registerNum',
    width: 150,
  },
  {
    title: '报名学校类别',
    dataIndex: 'registerType',
    width: 120,
  },
  {
    title: '应聘学校学校',
    dataIndex: 'registerSchool',
    width: 120,
  },
  {
    title: '应聘岗位',
    dataIndex: 'jobCode',
    width: 80,
  },
  {
    title: '姓名',
    dataIndex: 'actualName',
    width: 80,
    ellipsis: true,
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 70,
    ellipsis: true,
  },
  {
    title: '身份证',
    dataIndex: 'card',
    width: 170,
    ellipsis: true,
  },
  {
    title: '手机号码',
    dataIndex: 'phone',
    width: 100,
  },
  {
    title: '出生年月',
    width: 110,
    dataIndex: 'birthday',
    ellipsis: true,
  },
  {
    title: '民族',
    dataIndex: 'ethnicGroupId',
    width: 80,
  },
  {
    title: '邮箱',
    width: 150,
    dataIndex: 'email',
    ellipsis: true,
  },
  {
    title: '通讯地址',
    width: 100,
    dataIndex: 'mailAddress',
    ellipsis: true,
  },
  {
    title: '邮政编码',
    width: 100,
    dataIndex: 'postalCode',
  },
  {
    title: '普通话等级',
    width: 100,
    dataIndex: 'mandarin',
  },
  {
    title: '户籍所在地',
    width: 160,
    dataIndex: 'houseLocation',
  },
  {
    title: '政治面貌',
    dataIndex: 'political',
    width: 110,
  },
  {
    title: '婚姻状况',
    dataIndex: 'marital',
    width: 100,
  },
  {
    title: '学历',
    dataIndex: 'education',
    width: 110,
  },
  {
    title: '学位',
    dataIndex: 'academicDegree',
    width: 110,
  },

  {
    title: '外语等级',
    dataIndex: 'english',
    width: 110,
  },
 
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 120,
  },
]);
// 表格所有数据
const tableData = ref([]);
function tabClick(val) {
  queryForm.isPass = val
  console.log(queryForm.isPass)
  ajaxQuery();
}

// 上传附件
const open = ref(false);
const showModal = () => {
  open.value = true;
};
const fileKey = ref('')
// File list and progress
const fileList = ref([]);
const fileName = ref('');
const percent = ref(0);
const handleCancel = () => {
  fileList.value = [];
  percent.value = 0;
};
const handleOk = (e) => {
  let fileKeyobj = {
    fileKey: fileKey.value,
  };
  registrationReviewApi.uploadZip(fileKeyobj);
  // 点击确定关闭弹框
  open.value = false;
  percent.value = 0;
  message.success('文件上传成功！');
};
function downloadFiles() {
  let link = document.createElement('a'); // 创建下载的实体标签
  link.href = baseUrl + '/upload/' + queryFormState.fileUrl; // 创建下载的链接
  link.download = '附件' + '.zip'; // 下载的文件名
  link.click(); // 执行下载
  link.remove();
}



function uploadProgressCallback(progressEvent) {
  // 计算进度，progressEvent.loaded是已上传的字节数，progressEvent.total是需要上传的总字节数
  const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  percent.value = progress;
}
const customRequestFile = (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  formData.append('folder', 2);
  fileApi.uploadZip(formData, uploadProgressCallback).then((res) => {
    if (res.code === 0) {
      // queryFormState.fileUrl = res.data.fileKey;
      // fileName.value = res.data.fileName;
      fileKey.value = res.data.fileKey
    }
  });
};
// --------------------------- 查询 ---------------------------
const queryFormState = {
  isPass: 0,
  pageNum: 1,
  pageSize: PAGE_SIZE,
  searchCount: true,
  registerSchool: useUserStore().registerSchool,
  formState: ['2025-05-01 00:00:00'],
  fileUrl: '', //文件
  fileKey: '',
};
const queryForm = reactive({ ...queryFormState });
const tableLoading = ref(false);

const total = ref(0);

const filterOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

function onSearch() {
  queryForm.pageNum = 1;
  ajaxQuery();
}

function resetQuery() {
  // searchDate.value = [];
  Object.assign(queryForm, queryFormState);
  ajaxQuery();
}

async function ajaxQuery() {
  try {
    tableLoading.value = true;
    let responseModel = await registrationReviewApi.queryPage(queryForm);
    const list = responseModel.data.list;
    total.value = responseModel.data.total;
    tableData.value = list;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// --------------------------- 增加、修改、详情 ---------------------------

const detailFormRef = ref(null);
function examine(enterpriseId) {
  // detailFormRef.value.showModal(enterpriseId);
  detailFormRef.value.showModal(enterpriseId, 'examine');
}

function detail(enterpriseId) {
  detailFormRef.value.showModal(enterpriseId);
}
// 下载按钮
function downloadFile() {
  registrationReviewApi
    .downloadFile({
      employeeIds: selectedRowKeyList.value.length ? selectedRowKeyList.value : null,
      registerSchool: queryForm.registerSchool,
      isPass: queryForm.isPass,//isPass传传活的值queryForm.isPass，如果只传一个页面值给一个0
      formState: queryForm.formState,
    })
    .then((res) => {
      const url = window.URL.createObjectURL(new Blob([res.data], { type: res.headers['content-type'] }));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '教师招聘报名信息');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    });
}
// 下载附件
function downloadFile2() {
  registrationReviewApi
    .downloadFile2({
      employeeIds: selectedRowKeyList.value.length ? selectedRowKeyList.value : null,
      registerSchool: queryForm.registerSchool,
      isPass: queryForm.isPass,//isPass传传活的值queryForm.isPass，如果只传一个页面值给一个0,
      formState: queryForm.formState,
    })
    .then((res) => {
      const url = window.URL.createObjectURL(new Blob([res.data], { type: res.headers['content-type'] }));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '附件');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    });
}
const tableDataref = ref(null);
// 导出表格
function exportToExcel() {
  registrationReviewApi
    .exportToExcel({
      employeeIds: selectedRowKeyList.value.length ? selectedRowKeyList.value : null,
      registerSchool: queryForm.registerSchool,
      isPass: queryForm.isPass,//isPass传传活的值queryForm.isPass，如果只传一个页面值给一个0,,
      formState: queryForm.formState,
    })
    .then((res) => {
      const url = window.URL.createObjectURL(new Blob([res.data], { type: res.headers['content-type'] }));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '学校教师招聘报名信息.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    });
}
const schooleOptions = ref([]);
// 表格选择
function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}
onMounted(async () => {
  ajaxQuery();
  const res = await loginApi.ethnicGroupSelect();
  ethnicGroupList.value = res.data.data.map((i) => {
    return i.ethnicGroupName;
  });

  // const registerType = await loginApi.schoolType();
  // registerTypeList.value = registerType.data.rows.map((i) => {
  //   return i.MC;
  // });

  const schooleList = await loginApi.schoolList();
  schooleOptions.value = schooleList.data.map((i) => {
    return { label: i.name, value: i.name };
  });
});
</script>
